package com.xltx.mail.service.Impl;

import com.sun.mail.util.MailSSLSocketFactory;
import com.xltx.mail.common.constant.MailConstant;
import com.xltx.mail.properties.MailProperties;
import com.xltx.mail.service.MailService;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @author liuyc
 * @ClassName MailServiceImpl
 * @Description 邮箱服务实现类
 * @Date 2022/1/17 11:09
 */
@Service
public class MailServiceImpl implements MailService {

    @Resource
    private MailProperties mailProperties;

    /**
     * 获取邮件配置
     *
     * @return Properties
     */
    public Properties properties() {
        Properties prop = new Properties();
        prop.setProperty("mail.host", mailProperties.getHost());
        prop.setProperty("mail.transport.protocol", mailProperties.getProtocol());
        prop.setProperty("mail.smtp.auth", mailProperties.getAuth());

        if (MailConstant.MAIL_QQ.equals(mailProperties.getType())) {
            try {
                MailSSLSocketFactory factory = new MailSSLSocketFactory();
                factory.setTrustAllHosts(true);
                prop.put("mail.smtp.ssl.enable", "true");
                prop.put("mail.smtp.ssl.socketFactory", factory);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return prop;
    }

    /**
     * 创建一个session对象
     *
     * @return Session
     */
    public Session session() {
        Properties properties = properties();
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailProperties.getEmail(), mailProperties.getCode());
            }
        });
        // 开启debug模式
        session.setDebug(mailProperties.getDebug());
        return session;
    }

    @Override
    public void sendTextMail(@NonNull String recipient, @NonNull String title, String content) {
        try {
            Session session = session();
            // 获取连接对象
            Transport transport = session.getTransport();
            // 连接服务器
            transport.connect(mailProperties.getHost(), mailProperties.getEmail(), mailProperties.getCode());
            // 创建邮件
            MimeMessage mimeMessage = createMail(session, recipient, title, content);
            // 发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            // 关闭连接
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建邮件
     *
     * @param session   session
     * @param recipient 收件人
     * @param title     主题
     * @param content   内容
     * @return MimeMessage
     */
    public MimeMessage createMail(@NonNull Session session, @NonNull String recipient, @NonNull String title, String content) {
        // 创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            // 邮件发送人
            mimeMessage.setFrom(new InternetAddress(mailProperties.getEmail()));
            // 邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            // 邮件标题
            mimeMessage.setSubject(title, "UTF-8");
            // 邮件内容
            mimeMessage.setContent(content, "text/html;charset=UTF-8");
            // 设置发件时间
            mimeMessage.setSentDate(new Date());
            // 保存设置
            mimeMessage.saveChanges();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mimeMessage;
    }
}
